package cn.newgrand.netcall.integration.sms;

import org.jivesoftware.Spark;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.UserManager;
import org.jivesoftware.spark.component.TitlePanel;
import org.jivesoftware.spark.ui.RosterPickList;
import org.jivesoftware.spark.util.StringUtils;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscripts;

import cn.newgrand.common.CommonUtil;
import cn.newgrand.common.StringUtil;
import cn.newgrand.netcall.imp.search.contact.ContactSearchResultPanel;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 * @author SidneyRen E-mail:SidneyRen@hotmail.com
 * @version create time：2010-12-16 下午04:56:22
 * 类说明
 */
public class SMSPanel extends JPanel {
	
	
	private DefaultListModel invitedUsers = new DefaultListModel();
	private JDialog dlg;
	private final ContactSearchResultPanel contactSearchResult = new ContactSearchResultPanel();

	private UserManager userManager = SparkManager.getUserManager();

	TitlePanel titlePanel;

	private static SMSManager smsManager = SMSManager.getInstance();

	private Collection<String> invalidUsers = new ArrayList<String>();
	private SMS smsEntity = new SMS();

	public SMSPanel() {
		initComponents();

		browseButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent actionEvent) {
				RosterPickList browser = new RosterPickList();
				Collection col = browser.showRoster(dlg, false);

				for (Object aCol : col) {
					String jid = (String) aCol;
					String temp = org.jivesoftware.spark.util.StringUtils
							.combineWithBracket(
									userManager.getUserNicknameFromJID(jid),
									jid);
					if (!invitedUsers.contains(temp)) {
						invitedUsers.addElement(temp);
					}

				}
			}
		});

		// Add Listener to list
		invitedUserList.addMouseListener(new MouseAdapter() {
			public void mouseReleased(MouseEvent mouseEvent) {
				if (mouseEvent.isPopupTrigger()) {
					showPopup(mouseEvent);
				}
			}

			public void mousePressed(MouseEvent mouseEvent) {
				if (mouseEvent.isPopupTrigger()) {
					showPopup(mouseEvent);
				}
			}
		});

	}

	private void showPopup(MouseEvent e) {
		final JPopupMenu popup = new JPopupMenu();
		final int index = invitedUserList.locationToIndex(e.getPoint());

		Action removeAction = new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				invitedUsers.remove(index);
			}
		};

		removeAction.putValue(Action.NAME, Res.getString("menuitem.remove"));
		removeAction.putValue(Action.SMALL_ICON,
				SparkRes.getImageIcon(SparkRes.SMALL_DELETE));

		popup.add(removeAction);

		popup.show(invitedUserList, e.getX(), e.getY());

	}

	public void inviteUsersToRoom(Collection jids) {
		// roomsField.setText(roomName);

		JFrame parent = SparkManager.getChatManager().getChatContainer()
				.getChatFrame();
		if (parent == null || !parent.isVisible()) {
			parent = SparkManager.getMainWindow();
		}

		// Add jids to user list
		if (jids != null) {
			for (Object jid : jids) {
				invitedUsers.addElement(org.jivesoftware.spark.util.StringUtils
						.combineWithBracket(userManager
								.getUserNicknameFromJID((String) jid),
								(String) jid));
			}
		}

		final JOptionPane pane;

		// Create the title panel for this dialog
		titlePanel = new TitlePanel(
				Res.getString("title.invite.to.conference"),
				Res.getString("message.invite.users.to.conference"),
				SparkRes.getImageIcon(SparkRes.BLANK_IMAGE), true);
		Object[] options = { Res.getString("invite"), Res.getString("cancel") };
		pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE,
				JOptionPane.OK_CANCEL_OPTION, null, options);

		// mainPanel.add(pane, BorderLayout.CENTER);

		final JOptionPane p = new JOptionPane();
		// dlg = p.createDialog(parent,
		// Res.getString("title.conference.rooms"));
		dlg = p.createDialog(parent, "短信发送");
		dlg.getLayeredPane().add(contactSearchResult, JLayeredPane.POPUP_LAYER);
		dlg.setModal(false);
		dlg.pack();
		dlg.setSize(507, 500);
		// dlg.setResizable(false);
		dlg.setContentPane(this);
		dlg.setLocationRelativeTo(parent);

		contactSearchResult.initListenerForInput(jidField, invitedUsers);
		contactSearchResult.setLocation(44, 55);

		dlg.setVisible(true);
		dlg.toFront();
		jidField.requestFocus();
	}

	final MouseListener searchMouseListener = new MouseAdapter() {

	};

	public JTextField getJidField() {
		return jidField;
	}
		
		public  TitlePanel getTitlePanel() {
			return titlePanel;
		}
		
		private void initComponents() {

	        jPanel1 = new javax.swing.JPanel();
	        jScrollPane1 = new javax.swing.JScrollPane();
	        invitedUserList = new javax.swing.JList();
	        smsLable = new javax.swing.JLabel();
	        jPanel3 = new javax.swing.JPanel();
	        browseButton = new javax.swing.JButton();
	        jidField = new javax.swing.JTextField();
	        jPanel5 = new javax.swing.JPanel();
	        sendButton = new javax.swing.JButton();
	        jPanel4 = new javax.swing.JPanel();
	        jRadioButton1 = new javax.swing.JRadioButton();
	        jPanel2 = new javax.swing.JPanel();
	        userlistLabel = new javax.swing.JLabel();
	        smsTextArea = new javax.swing.JTextArea();
	        jScrollPane2 = new javax.swing.JScrollPane();
	        searchLabel = new javax.swing.JLabel();

//	        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

	        jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
	        jScrollPane1.setAutoscrolls(true);
	        jScrollPane1.setOpaque(false);

	        invitedUserList.setModel(invitedUsers);
	        jScrollPane1.setViewportView(invitedUserList);

	        userlistLabel.setText("接收者列表：(鼠标右键删除)");

	        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
	        jPanel1.setLayout(jPanel1Layout);
	        jPanel1Layout.setHorizontalGroup(
	            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
            .addComponent(userlistLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
	            
//	            .addGroup(jPanel1Layout.createSequentialGroup()
//	                .addComponent(userlistLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
//	                .addContainerGap(82, Short.MAX_VALUE))
//	            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
	        );
	        jPanel1Layout.setVerticalGroup(
	            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(jPanel1Layout.createSequentialGroup()
	                .addComponent(userlistLabel)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 377, javax.swing.GroupLayout.PREFERRED_SIZE))
	        );
	        
	        searchLabel.setText("查找添加：");
	        browseButton.setText("联系人列表");

	        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
	        jPanel3.setLayout(jPanel3Layout);
	        jPanel3Layout.setHorizontalGroup(
	            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(jPanel3Layout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(searchLabel)
	                .addComponent(jidField, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(browseButton)
	                .addContainerGap(210, Short.MAX_VALUE))
	        );
	        jPanel3Layout.setVerticalGroup(
	            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
	                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
	                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(browseButton)
	                    .addComponent(searchLabel)
	                    .addComponent(jidField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
	        );

	        sendButton.setText("发送短信");
	        sendButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                sendButtonActionPerformed(evt);
	            }
	        });

	        smsLable.setText("消息内容：");

	        jRadioButton1.setText("添加发送者姓名");
	        jRadioButton1.setSelected(true);

	        smsTextArea.setColumns(20);
	        smsTextArea.setRows(5);
	        smsTextArea.setLineWrap(true);
	        jScrollPane2.setViewportView(smsTextArea);

	        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
	        jPanel2.setLayout(jPanel2Layout);
	        jPanel2Layout.setHorizontalGroup(
	            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(jPanel2Layout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
	                        .addComponent(smsLable, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
	                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
	                        .addComponent(jRadioButton1)
	                        .addGap(29, 29, 29))
	                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
	                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
	                        .addContainerGap())))
	        );
	        jPanel2Layout.setVerticalGroup(
	            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(jPanel2Layout.createSequentialGroup()
	                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(jRadioButton1)
	                    .addComponent(smsLable))
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
	                .addGap(10, 10, 10))
	        );
	        

	        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
	        jPanel4.setLayout(jPanel4Layout);
	        jPanel4Layout.setHorizontalGroup(
	            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(jPanel4Layout.createSequentialGroup()
	                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(jPanel4Layout.createSequentialGroup()
	                        .addContainerGap()
	                        .addComponent(jRadioButton1))
	                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
	        );
	        jPanel4Layout.setVerticalGroup(
	            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(jPanel4Layout.createSequentialGroup()
	                .addComponent(jRadioButton1)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
	        );

	        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
	        jPanel5.setLayout(jPanel5Layout);
	        jPanel5Layout.setHorizontalGroup(
	            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(jPanel5Layout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(jPanel5Layout.createSequentialGroup()
	                        .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
	                        .addContainerGap())
	                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
	                        .addComponent(sendButton)
	                        .addGap(53, 53, 53))))
	        );
	        jPanel5Layout.setVerticalGroup(
	            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(jPanel5Layout.createSequentialGroup()
	                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
	                .addComponent(sendButton))
	        );

	        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
	        this.setLayout(layout);
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(layout.createSequentialGroup()
	                        .addContainerGap()
	                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                        .addGap(18, 18, 18)
	                        .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE))
	                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addContainerGap())
	        );
	        layout.setVerticalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
	                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addGap(18, 18, 18)
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                    .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addContainerGap())
	        );
	    }// </editor-fold>

	private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {

		int size = invitedUserList.getModel().getSize();
		StringBuffer tranRecvs = new StringBuffer();
		final List<SMSContact> receivers = new ArrayList<SMSContact>();
		final List<String> recvUsersList = new ArrayList<String>();
		
		//选中list所有的值
		if (invitedUsers.getSize() > 0) {
            invitedUserList.setSelectionInterval(0, invitedUsers.getSize() - 1);
        }
		
		Object[] jids = invitedUserList.getSelectedValues();
		SMSContact sender = new SMSContact();
		
		sender.setJid(SparkManager.getSessionManager().getUsername());
		smsEntity.setSender(sender);
		
		//短信服务是否可用
		if(!SMSManager.isSMSServerAvailable){
			JOptionPane.showMessageDialog(dlg,
					Res.getString("message.sms.server.error.unavailable"),
					Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
			return;
		}
		//内容是否为空
		String content = smsTextArea.getText();
		if (!StringUtil.isEmpty(content)) {
			if(jRadioButton1.isSelected()){
				content=SparkManager.getUserManager().getNickname()+":"+content;//+"[来自NETCALL消息，可直接回复]";
			}
			smsEntity.setContent(content);
		}else{
			JOptionPane.showMessageDialog(dlg,
					Res.getString("message.sms.content.error.null"),
					Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
			return;
		}

		//接受者是否为空
		if (size == 0) {
			JOptionPane.showMessageDialog(dlg,
					Res.getString("message.sms.recv.users.null"),
					Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		if (invitedUsers.getSize() > 0) {
			invitedUserList.setSelectionInterval(0, invitedUsers.getSize() - 1);
		}
		
		//组装短信接收者
		final int no = jids != null ? jids.length : 0;
		for (int i = 0; i < no; i++) {
			try {
				String tempJID = org.jivesoftware.spark.util.StringUtils
						.getStrInLastBrackets((String) jids[i]);
				
				String phone = SparkManager.getVCardManager().getVCard(tempJID)
						.getPhoneWork("CELL");
				if (StringUtil.isEmpty(phone)) {
					invalidUsers.add((String) jids[i]);

				} else {
					String recvName = cn.newgrand.netcall.common.StringUtilCommon.parseName(tempJID);
					String nickName = SparkManager.getUserManager().getUserNicknameFromJID(tempJID);
					//构建接收者列表，存于短信记录中
					tranRecvs.append(nickName).append("(").append(phone).append(")").append(";");
					
					SMSContact recv = new SMSContact();
					recv.setPhone(phone);
					recv.setName(recvName);
//					recvUsersList.add(tempJID);
					receivers.add(recv);
				}
			} catch (NullPointerException ee) {
				Log.error(ee);
			}
		}
		
		//判断接收者的手机是否为空,如果全为空则报错
		if(CommonUtil.isEmpty(receivers)){
			JOptionPane.showMessageDialog(dlg,
					Res.getString("message.sms.recv.phones.error.null"),
					Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		smsEntity.setReceivers(receivers);
				
		
		String smsTranscript = Res.getString("message.sms.transcript.content",tranRecvs.toString(),content);

		//判断提醒发送者，接收手列表中存在没有设置手机号码的联系人
		if(!CommonUtil.isEmpty(invalidUsers)){
			StringBuffer sb = new StringBuffer();
			for (String str : invalidUsers) {
				sb.append(str).append(";");
			}
			final int ok = JOptionPane.showConfirmDialog(dlg,
					Res.getString("message.sms.users.phone.error.null",sb.toString()),
					Res.getString("title.error"), JOptionPane.YES_NO_OPTION);
			if(ok == JOptionPane.OK_OPTION){
				try {
					smsManager.sendSMS(smsEntity,SMSManager.REPLY);
					smsManager.saveTranscript(smsTranscript);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.error(e.getMessage(),e);
				}
				
				JOptionPane.showMessageDialog(dlg,
						Res.getString("message.sms.send.success"),
						Res.getString("title.success"), JOptionPane.INFORMATION_MESSAGE);
				dlg.dispose();
				return;
			}
		}
		
		
		try {
			smsManager.sendSMS(smsEntity,SMSManager.REPLY);
			smsManager.saveTranscript(smsTranscript);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.error(e.getMessage(),e);
		}
		
		
		JOptionPane.showMessageDialog(dlg,
				Res.getString("message.sms.send.success"),
				Res.getString("title.success"), JOptionPane.INFORMATION_MESSAGE);
		dlg.dispose();
	}                                


	    // Variables declaration - do not modify
	    private javax.swing.JButton browseButton;
	    private javax.swing.JButton sendButton;
	    private javax.swing.JLabel userlistLabel;
	    private javax.swing.JLabel smsLable;
	    private javax.swing.JList invitedUserList;
	    private javax.swing.JPanel jPanel1;
	    private javax.swing.JPanel jPanel2;
	    private javax.swing.JPanel jPanel3;
	    private javax.swing.JPanel jPanel4;
	    private javax.swing.JPanel jPanel5;
	    private javax.swing.JRadioButton jRadioButton1;
	    private javax.swing.JScrollPane jScrollPane1;
	    private javax.swing.JTextField jidField;
	    private javax.swing.JTextArea smsTextArea;
	    private javax.swing.JScrollPane jScrollPane2;
	    private javax.swing.JLabel searchLabel;
	    // End of variables declaration
		
	}

